package controller.UserController;

import bean.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.AppVariable;
import common.ResultAjax;
import services.UserService;
import services.impl.UserServiceImpl;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/save")
public class SaveServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        //判断是否登录
        HttpSession session = req.getSession(false);
        if (session == null) {
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"未登录，请先登录！"));
            resp.getWriter().write(respJson);
            return ;
        }
        //获取参数
        String nickname = req.getParameter("nickname").trim();
        String phoneNumber = req.getParameter("phoneNumber").trim();
        String sex = req.getParameter("sex").trim();

        System.out.println(nickname);
        System.out.println(phoneNumber);
        System.out.println(sex);


        //判断参数是否合法
        // 只需要判断手机号码即可
        if(StringUtil.isEmpty(phoneNumber)||phoneNumber.length() != 11 || !phoneNumber.matches("\\d+")){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"参数有误！"));
            resp.getWriter().write(respJson);
            return ;
        }
        //调用Services层更新数据库
        User user = (User) session.getAttribute(AppVariable.SESSION_USERINFO_KEY);
        if(user==null){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"用户不存在，请重新登录！"));
            resp.getWriter().write(respJson);
            return ;
        }

        String gender = (sex.equals("男")) ? "1" : (sex.equals("女")) ? "0" : "2";
        int ret = userService.upDataByUid(user.getUid(), phoneNumber, nickname, gender);
        if (ret==1){
            String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(null));
            resp.getWriter().write(respJson);
            return ;
        }
        String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"保存失败"));
        resp.getWriter().write(respJson);
    }
}
